#!/usr/bin/env perl

BEGIN
{
    unshift(@INC, '.');
    require Data::Dumper;
    require LifeRay;
}

sub read_folders()
{
    my @folders = LifeRay::query('SELECT uuid_, folderId, parentFolderId, name, description FROM dlfolder');
    return map(($_->{folderId} => $_), @folders);
}

sub read_files($)
{
    my ($folders) = @_;
    my @files = LifeRay::query('SELECT uuid_, fileEntryId, version, folderId, userId, createDate, modifiedDate, name, title, description FROM dlfileentry');
    foreach my $file (@files)
    {
	# print Data::Dumper->Dump([$file]);
	push(@{$folders->{$file->{folderId}}{FILES}}, $file);
    }
}

sub render_folder($$$)
{
    my ($folders, $folder_id, $depth) = @_;
    my $folder = $folders->{$folder_id};
    if ($folder->{RENDERED})
    {
	print Data::Dumper->Dump([$folder]);
	die;
    }
    print ''.('  ' x $depth)."[$folder->{name}] ($folder->{folderId})\n";
    my @child_ids = grep($folders->{$_}{parentFolderId} == $folder_id, keys(%{$folders}));
    foreach my $child_id (@child_ids)
    {
	render_folder($folders, $child_id, $depth + 1);
    }
    foreach my $file (@{$folder->{FILES}})
    {
	print ''.('  ' x ($depth + 1))."$file->{title} ($file->{fileEntryId})\n";
    }
    ++$folder->{RENDERED};
}    

my %folders = read_folders();
read_files(\%folders);

foreach my $folder_id (keys(%folders))
{
    next if ($folders{$folder_id}{parentFolderId});
    render_folder(\%folders, $folder_id, 0);
}
die if (grep(!$folders{$_}{RENDERED}, keys(%folders)));
